package com.weishi.project.training.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weishi.common.utils.DateUtils;
import com.weishi.project.api.vo.WeekClassHourAndKilometersVo;
import com.weishi.project.api.vo.WeekDetailsVo;
import com.weishi.project.api.vo.WeekTypeCountVo;
import com.weishi.project.sport.home.vo.QueryDateVO;
import com.weishi.project.system.domain.SysUser;
import com.weishi.project.system.service.ISysUserService;
import com.weishi.project.training.domain.AnnualPlan;
import com.weishi.project.training.domain.TrainingDay;
import com.weishi.project.training.domain.TrainingWeek;
import com.weishi.project.training.mapper.TrainingWeekMapper;
import com.weishi.project.training.service.ITrainingDayService;
import com.weishi.project.training.service.ITrainingWeekService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * trainingWeekService业务层处理
 */
@Service
public class TrainingWeekServiceImpl extends ServiceImpl<TrainingWeekMapper, TrainingWeek> implements ITrainingWeekService {

    @Autowired
    private TrainingWeekMapper trainingWeekMapper;

    @Autowired
    private ITrainingDayService trainingDayService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询trainingWeek列表
     */
    @Override
    public List<TrainingWeek> selectTrainingWeekList(TrainingWeek trainingWeek) {
        List<TrainingWeek> list = trainingWeekMapper.selectTrainingWeekList(trainingWeek);
        for (TrainingWeek trainingWeek1 : list) {
            if (trainingWeek1.getTeamLeader() != null)
                trainingWeek1.setTeamLeaderName(sysUserService.selectUserByCache(trainingWeek1.getTeamLeader()).getUserName());
            if (trainingWeek1.getHeadCoach() != null)
                trainingWeek1.setHeadCoachName(sysUserService.selectUserByCache(trainingWeek1.getHeadCoach()).getUserName());
            if (trainingWeek1.getSpecialCoach() != null)
                trainingWeek1.setSpecialCoachName(sysUserService.selectUserByCache(trainingWeek1.getSpecialCoach()).getUserName());
            if (trainingWeek1.getFitnessCoach() != null)
                trainingWeek1.setFitnessCoachName(sysUserService.selectUserByCache(trainingWeek1.getFitnessCoach()).getUserName());
            if (trainingWeek1.getTeamDoctor() != null)
                trainingWeek1.setTeamDoctorName(sysUserService.selectUserByCache(trainingWeek1.getTeamDoctor()).getUserName());
        }
        return list;
    }

    @Override
    public List<AnnualPlan> getAnnualPlan() {
        return trainingWeekMapper.getAnnualPlan();
    }

    /**
     * 根据id查看周计划详情
     *
     * @param id
     * @return TrainingWeek
     */
    @Override
    public TrainingWeek getTrainingWeekById(int id) {
        return trainingWeekMapper.getTrainingWeekById(id);
    }

    @Override
    public void updateTrainingWeek(TrainingWeek trainingWeek) {
        trainingWeekMapper.updateTrainingWeek(trainingWeek);
    }

    @Override
    public TrainingWeek selectTrainingWeekByWeek(Integer annualPlanId, Integer id) {
        Map<String, Object> map = new HashMap<>();
        map.put("annualPlanId", annualPlanId);
        map.put("id", id);
        TrainingWeek trainingWeek = trainingWeekMapper.selectTrainingWeekByWeek(map);
        return trainingWeek;
    }

    @Override
    public List<SysUser> getSysUerList() {
        return trainingWeekMapper.getSysUerList();
    }

    @Override
    public List<WeekTypeCountVo> queryWeekTypeCount(Map<String, Object> map) {
        return trainingWeekMapper.queryWeekTypeCount(map);
    }

    @Override
    public List<WeekDetailsVo> getWeekDetails(int weekId) {
        return trainingWeekMapper.getWeekDetails(weekId);
    }


    @Override
    public TrainingWeek selectTrainingWeekByDay(Date date) {
        Map<String, Object> map = new HashMap<>();
        map.put("day", DateUtils.parseDateToStr("yyyy-MM-dd", date));
        return trainingWeekMapper.selectTrainingWeekByDay(map);
    }

    @Override
    public List<WeekClassHourAndKilometersVo> getWeekClassHourAndKilometersVoList(Map<String, Object> params) {
        return trainingWeekMapper.getWeekClassHourAndKilometersVoList(params);
    }

    @Override
    public void saveTrainingWeek(TrainingWeek trainingWeek) {
        trainingWeekMapper.saveTrainingWeek(trainingWeek);
    }

    @Override
    public void removeTrainingWeek(int id) {
        trainingWeekMapper.removeTrainingWeek(id);
    }

    @Override
    @Transactional
    public String synchronizeData(Integer oldWeekId, Integer weekId) {
        TrainingWeek oldTrainingWeek = trainingWeekMapper.getTrainingWeekById(oldWeekId);
        List<TrainingDay> oldTrainingDays = this.trainingDayService.getTrainingDayByWeekId(oldWeekId);

        TrainingWeek trainingWeek = trainingWeekMapper.getTrainingWeekById(weekId);
        List<TrainingDay> trainingDays = this.trainingDayService.getTrainingDayByWeekId(weekId);
        Date startWeek = trainingWeek.getStartTime();
        Date endtWeek = trainingWeek.getEndTime();
        if (oldTrainingDays == null || oldTrainingDays.size() == 0) {
            return "复用周无训练项目";
        }
        if (trainingDays != null && trainingDays.size() > 0) {
            return "当前周已存在训练项目,无法复用";
        }
        if (startWeek == null || startWeek==null) {
            return "无效周";
        }

        //同步周数据
        trainingWeek.setStrength(oldTrainingWeek.getStrength());
        trainingWeek.setTrainingLocationId(oldTrainingWeek.getTrainingLocationId());
        trainingWeek.setTrainingLocationName(oldTrainingWeek.getTrainingLocationName());
        trainingWeek.setTeamLeader(oldTrainingWeek.getTeamLeader());
        trainingWeek.setTeamLeaderName(oldTrainingWeek.getTeamLeaderName());
        trainingWeek.setHeadCoach(oldTrainingWeek.getHeadCoach());
        trainingWeek.setHeadCoachName(oldTrainingWeek.getHeadCoachName());
        trainingWeek.setSpecialCoach(oldTrainingWeek.getSpecialCoach());
        trainingWeek.setSpecialCoachName(oldTrainingWeek.getSpecialCoachName());
        trainingWeek.setFitnessCoach(oldTrainingWeek.getFitnessCoach());
        trainingWeek.setFitnessCoachName(oldTrainingWeek.getFitnessCoachName());
        trainingWeek.setTeamDoctor(oldTrainingWeek.getTeamDoctor());
        trainingWeek.setTeamDoctorName(oldTrainingWeek.getTeamDoctorName());
        trainingWeek.setOutline(oldTrainingWeek.getOutline());
        trainingWeek.setType(oldTrainingWeek.getType());
        trainingWeek.setPlan(oldTrainingWeek.getPlan());
        trainingWeek.setSummary(oldTrainingWeek.getSummary());
        trainingWeek.setMemo(oldTrainingWeek.getMemo());
        trainingWeek.setStartTime(null);
        trainingWeek.setEndTime(null);
        trainingWeek.setCtime(null);
        trainingWeekMapper.updateTrainingWeek(trainingWeek);

        //同步训练日数据
        for (TrainingDay trainingDay : oldTrainingDays) {
            Date day = getDate(DateUtils.parseDate(trainingDay.getDay()),startWeek,endtWeek);
            if(day==null){
                continue;
            }
            TrainingDay temp = new TrainingDay();
            temp.setWeekId(weekId);
            temp.setDay(DateUtils.parseDateToStr("yyyy-MM-dd",day));
            temp.setFourSeasons(trainingDay.getFourSeasons());
            temp.setFirstLevel(trainingDay.getFirstLevel());
            temp.setFirstLevelName(trainingDay.getFirstLevelName());
            temp.setSecondLevel(trainingDay.getSecondLevel());
            temp.setSecondLevelName(trainingDay.getSecondLevelName());
            temp.setClassHour(trainingDay.getClassHour());
            temp.setIdealKilometers(trainingDay.getIdealKilometers());
            temp.setWarmUpKilometers(trainingDay.getWarmUpKilometers());
            temp.setNumberGroups(trainingDay.getNumberGroups());
            temp.setGapTime(trainingDay.getGapTime());
            temp.setStrength(trainingDay.getStrength());
            temp.setHr(trainingDay.getHr());
            temp.setHrTwo(trainingDay.getHrTwo());
            temp.setSr(trainingDay.getSr());
            temp.setSrTwo(trainingDay.getSrTwo());
            temp.setStartTime(trainingDay.getStartTime());
            temp.setEndTime(trainingDay.getEndTime());
            temp.setCtime(new Date());
            trainingDayService.save(temp);
        }
        return "success";
    }

    /**
     * 同步其他周日期
     * @param reference  参考时间
     * @param weekStart
     * @param weekEnd
     * @return
     */
    private static Date getDate(Date reference, Date weekStart, Date weekEnd) {
        Calendar c = Calendar.getInstance();
        c.setTime(reference);
        int weekIndex = c.get(Calendar.DAY_OF_WEEK);

        c.setTime(weekStart);
        c.set(Calendar.DAY_OF_WEEK,weekIndex);
        Date ret = c.getTime();

        if(DateUtils.isDateBetweenOtherDate(weekStart,weekEnd,ret)){
            return ret;
        }else{
            c.setTime(weekEnd);
            c.set(Calendar.DAY_OF_WEEK,weekIndex);
            ret = c.getTime();
        }

        if(DateUtils.isDateBetweenOtherDate(weekStart,weekEnd,ret)){
            return ret;
        }
        return null;
    }

    public static void main(String[] args) {
        Date reference = DateUtils.parseDate("2020-12-13");
        Date weekStart = DateUtils.parseDate("2020-12-14");
        Date weekEnd = DateUtils.parseDate("2020-12-20");

        Date aa = getDate(reference,weekStart,weekEnd);
        System.out.println(aa);
    }


    /**
     * 运动员 -- 本周训练数据 -- 查询日期
     */
    @Override
    public List<QueryDateVO> getQueryDate(String day , Integer week) {
        return trainingWeekMapper.getQueryDate(day , week);
    }


    /**
     * 初始化周信息
     * @param annualPlan
     * @param annualPlanId
     */
    public void saveTrainingWeek(AnnualPlan annualPlan, Integer annualPlanId){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date ST = null;
        Date ED = null;
        try {
            ST = simpleDateFormat.parse(annualPlan.getStartTime());
            ED = simpleDateFormat.parse(annualPlan.getEndTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Date startTime = ST;
        Date endTime;
        boolean flag = true;
        int index = 1;
        while (flag){
            int weekNum = returnWeek(startTime);
            endTime = DateUtils.getSpecifiedDayAfter(startTime,7-weekNum);
            if(endTime.compareTo(ED)==0 || endTime.after(ED)){
                endTime = ED;
                flag = false;
            }
            TrainingWeek trainingWeek = new TrainingWeek();
            trainingWeek.setStartTime(startTime);
            trainingWeek.setEndTime(endTime);
            trainingWeek.setAnnualPlanId(annualPlanId);
            trainingWeek.setWeek(index++);
            trainingWeek.setCtime(new Date());
            this.save(trainingWeek);
            startTime = DateUtils.getSpecifiedDayAfter(endTime,1);
        }
    }

    /**
     * 判断日期是星期几
     *
     * @param time
     * @return String
     */
    private static int returnWeek(Date time) {
        Calendar cal = Calendar.getInstance();
        Integer[] weekDays = {7, 1, 2, 3, 4, 5, 6};
        try {
            cal.setTime(time);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
        if (w < 0)
            w = 0;
        return weekDays[w];
    }





}